package com.whfc.ms.websocket;


import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author xugouhceng
 * @desc WebSocket握手拦截器
 */
@Component
public class AuthHandshakeInterceptor implements HandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            SysUser user = null;
            //todo 测试用
            try {
                ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
                String userId = servletRequest.getServletRequest().getParameter("userId");
                if (!StringUtils.isEmpty(userId)) {
                    user = sysUserService.getUserById(Integer.valueOf(userId));
                    if (user != null) {
                        attributes.put(SessionAttr.MS_USER, user);
                        return true;
                    }
                }
            } catch (Exception ex) {
                logger.warn("", ex);
            }
            user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SessionAttr.MS_USER);
            logger.info("ws,连接开始,uri:{},sysUser:{}", request.getURI(), JSONUtil.toString(user));
            if (user != null) {
                attributes.put(SessionAttr.MS_USER, user);
                return true;
            }
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        logger.info("ws,连接完成,uri:{}", request.getURI());
    }
}
